import { Injectable, Injector } from '@angular/core';
import { CacheService } from '@delon/cache';
import { _HttpClient } from '@delon/theme';
import { ArrayService } from '@delon/util';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalService } from 'ng-zorro-antd/modal';

import { ApiResponse, ApiResToComponent, ErrorApiRequest, SuccessApiRequest } from '../datas';
import { LogAndColor, LoggerService } from './logger.service';
import { ShowModalService } from './show-modal.service';

/**
 * 主要是对一些常用的API返回方法进行封装和再处理，规范对返回数据的处理结构
 */
@Injectable()
export class CommBasicService {
    log: LoggerService;
    msg: NzMessageService;
    client: _HttpClient;
    modal: ShowModalService;
    modalSrv: NzModalService;
    arrSer: ArrayService;
    cache: CacheService;

    constructor(protected injector: Injector) {
        this.log = this.injector.get(LoggerService);
        this.msg = this.injector.get(NzMessageService);
        this.client = this.injector.get(_HttpClient);
        this.modal = this.injector.get(ShowModalService);
        this.modalSrv = this.injector.get(NzModalService);
        this.arrSer = this.injector.get(ArrayService);
        this.cache = this.injector.get(CacheService);
    }

    /**
     * 在API请求后，处理数据结果
     *
     * @param ev API请求返回的结果
     * @param log 输出LOG的信息 {msg: string|number, color: string}
     * @param code 错误码标识
     * @param failMsg 失败时是否提示消息
     * @param successMsg 成功时是否提供消息
     * @param failCallback 失败时的另外的处理方式
     */
    public doWithResponse<T>(
        ev: ApiResponse,
        log: LogAndColor = { msg: '获取数据成功', color: 'grey' },
        failMsg: boolean = true,
        successMsg: boolean = false,
        code: string | number = 200,
        failCallback?: (item: any) => void
    ): ApiResToComponent<T> {
        this.log.logObj(ev, log.msg, log.color);
        if (ev.code !== code) {
            if (failMsg) {
                this.msg.error(ev.msg ?? `${log.msg}失败！`);
            }
            if (failCallback) {
                failCallback(ev);
            }
            return new ErrorApiRequest<T>(ev).apiReturn;
        } else {
            if (successMsg) {
                this.msg.success(ev.msg ?? `${log.msg}成功！`);
            }
            return new SuccessApiRequest<T>(ev).apiReturn;
        }
    }
}
